using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using System.Text;

namespace System.Web.Core
{
    public class EntityListRequest : EntityRequest
    {
        #region Private Members

        private int? pageIndex = GetParameterValue<int?>(ParameterName.PageIndex);
        private int pageSize = 30;

        #endregion

        #region Public Properties

        public int? PageIndex
        {
            get
            {
                return pageIndex;
            }
            set
            {
                pageIndex = value;
            }
        }
        public int PageSize
        {
            get
            {
                return pageSize;
            }
            set
            {
                pageSize = value;
            }
        }

        #endregion

        #region Constructors

        public EntityListRequest()
        {
            if (PageIndex == null)
            {
                PageIndex = 0;
            }
            else
            {
                PageIndex--;
                if (PageIndex < 0)
                {
                    PageIndex = 0;
                }
            }
        }

        #endregion

        #region Public Methods

        public override BaseReply Send(BaseRequestBinder requestBinder)
        {
            BaseReply reply = requestBinder.Reply;
            reply.Reply = EntityManager.GetEntityList(requestBinder);
            return reply;
        }
        public override string GetReturnFieldString()
        {
            if (ReturnFields == null || ReturnFields.Count == 0)
            {
                ReturnFields = GetDefaultReturnFields();
            }
            if (!ReturnFields.Contains("EntityId"))
            {
                ReturnFields.Add("EntityId");
            }
            List<string> formattedFields = new List<string>();
            foreach (string field in ReturnFields)
            {
                formattedFields.Add("t." + field);
            }
            return string.Join(",", formattedFields.ToArray());
        }

        #endregion
    }

    public class TEntityListRequest<TEntity> : EntityListRequest where TEntity : Entity, new()
    {
        public TEntityListRequest()
        {
            Entity = new TEntity();
            ReturnFields = GetDefaultReturnFields();
        }
    }
}